

//
//  TheLoginViewController.h
//  HAODE
//
//  Created by panquanReabam.com on 15/9/8.
//  Copyright (c) 2015年 reabam.com. All rights reserved.

#import "TheLoginViewController.h"
#import "HttpRequest.h"
#import "RDVTabBarController.h"
#import "UIViewExt.h"
#import <objc/runtime.h>
#import <RongIMKit/RongIMKit.h>
#import "TheLoginView.h"
#import "ForgotPasswordViewController.h"
#import "RegistedViewController.h"
#import "ToBindCompanyViewController.h"
@interface TheLoginViewController ()<UITextFieldDelegate,UIGestureRecognizerDelegate,UINavigationControllerDelegate,UIScrollViewDelegate ,RCIMUserInfoDataSource,TheLoginViewDelegate>
@property (retain,nonatomic)UIImageView *recordBtn;
@end

@implementation TheLoginViewController

{
      MBProgressHUD *progressHud;
}
@synthesize alt = alt;
@synthesize mDelegate;
- (void)viewDidDisappear:(BOOL)animated

{
    
    [super viewDidDisappear:animated];
    
    
    
    self.navigationController.delegate = nil;
    
}
-(void)BackAction:(UIButton *)sender{
    
    [self.navigationController popToViewController:[self.navigationController.viewControllers objectAtIndex:0] animated:YES];
    
    
}

-(void)viewWillAppear:(BOOL)animated{
    
    [super viewWillAppear:animated];
    
    self.navigationController.delegate = self;
    
    self.navigationController.interactivePopGestureRecognizer.enabled = YES;
    self.navigationController.interactivePopGestureRecognizer.delegate = self;
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@""] forBarMetrics:UIBarMetricsDefault];
    self.navigationController.navigationBar.shadowImage =[[UIImage alloc] init];
    
    [[self rdv_tabBarController] setTabBarHidden:YES];
    self.navigationController.navigationBarHidden = NO;
    self.navigationController.navigationBar.barStyle = UIBaselineAdjustmentNone;
    UILabel *lineLabel=[[UILabel alloc] initWithFrame:CGRectMake(0, 43,ScreenWidth, 1)];
    [lineLabel setBackgroundColor:[UIColor colorWithRed:238.0/255.0 green:238.0/255.0 blue:238.0/255.0 alpha:1.0]];
    [self.navigationController.navigationBar addSubview:lineLabel];
    [self.navigationController.navigationBar setTintColor:[UIColor whiteColor]];
    [[UINavigationBar appearance] setBarTintColor:Color];
    
    UIImage* backImage = [UIImage imageNamed:@""];
    CGRect backframe = CGRectMake(0,0,23/2,41/2);
    UIButton* backButton= [[UIButton alloc] initWithFrame:backframe];
    [backButton setBackgroundImage:backImage forState:UIControlStateNormal];
    backButton.titleLabel.textAlignment=NSTextAlignmentLeft;
    UIBarButtonItem* leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    self.navigationItem.leftBarButtonItem = leftBarButtonItem;
    
}
-(void)viewDidLoad{
    
    
    [super viewDidLoad];
    
    
    self.title = @"用户登录";
    [self.navigationController.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:
                                                                     backColor,
                                                                     UITextAttributeTextColor,
                                                                     [UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:1],
                                                                     UITextAttributeTextShadowColor,
                                                                     [NSValue valueWithUIOffset:UIOffsetMake(0, 0)],
                                                                     UITextAttributeTextShadowOffset,
                                                                     [UIFont fontWithName:@"Helvetica Neue" size:tetlefot],
                                                                     UITextAttributeFont,nil]];
    
    
    
    
    
    
    
    
    
    [self initView];
       
    
    
}

- (void)initView
{
    TheLoginView *container = [[TheLoginView alloc]initWithFrame:self.view.bounds];
    container.mDelegate=self;
    [self.view addSubview:container];
    }

#pragma mark Event Handle

-(void)userName:(NSString *)userName pwd:(NSString *)password{

    if ([userName length] <1)
    {
        [self showAlertMessage:@"请输入账号"];
    }
    else{
     if ([password length] < 1)
        {
            [self showAlertMessage:@"请输入密码"];
        }
        else
        {
            [Global showIndeterminateHud:@"登录中，请稍后..." delay:30 view:self.view];
            NSMutableDictionary *params = [NSMutableDictionary new];
            [params setValue:userName forKey:@"mobile"];
            [params setValue:[MyMD5 md5:password] forKey:@"loginWord"];
            [HttpRequest requestData1:@"Common/Login" params:params success:^(BOOL isSuccess, SeverData *severDataDict) {
                if (isSuccess) {
                    if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==0) {
                        
                        [Global hideProgressHUDInternal:self.view];
                        [self RongYun];
                        NSLog(@"-------%@",severDataDict.dataDict);
                        
                        NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
                        [user setObject:[[severDataDict.dataDict objectForKey:@"DataLine"]objectForKey:@"companyId" ] forKey:@"companyId"];
                        [user setObject:[[severDataDict.dataDict objectForKey:@"DataLine"]objectForKey:@"tokenId" ] forKey:@"tokenId"];
                        [user setObject:[[severDataDict.dataDict objectForKey:@"DataLine"]objectForKey:@"userCode" ] forKey:@"userCode"];
                        [user setObject:[[severDataDict.dataDict objectForKey:@"DataLine"]objectForKey:@"userName" ] forKey:@"userName"];
                        [user setObject:[[severDataDict.dataDict objectForKey:@"DataLine"]objectForKey:@"companyName" ] forKey:@"companyName"];
                        [user setObject:[NSString stringWithFormat:@"%@",[[severDataDict.dataDict objectForKey:@"DataLine"]objectForKey:@"userStatus" ]] forKey:@"userStatus"];
                        
                        [user setObject:[NSString stringWithFormat:@"%@",[[severDataDict.dataDict objectForKey:@"DataLine"]objectForKey:@"groupId" ]] forKey:@"groupId"];
                        [user setObject:[[severDataDict.dataDict objectForKey:@"DataLine"] objectForKey:@"serverAddress"] forKey:@"serverAddress"];
                        
                        [user setObject:password forKey:@"passwordTextField"];
                        [user setObject:userName forKey:@"userNameTextField"];
                        [user setObject:[[severDataDict.dataDict objectForKey:@"DataLine"]objectForKey:@"userType" ]  forKey:@"userType"];
                        
                        [user synchronize];
                    
                        [mDelegate update:@""];
                        
                       
                        [self.navigationController popToViewController:[self.navigationController.viewControllers objectAtIndex:0] animated:YES];
                        
                        
                        
                    }else{
                        [Global hideProgressHUDInternal:self.view];
                        NSString *requestResultStr=[severDataDict.dataDict objectForKey:@"ResultString"];
                        [Global showTextHudSub:requestResultStr view:self.view];
                        
                    }
                    
                }
                else
                {
                    [Global hideProgressHUDInternal:self.view];
                    
                    [Global showTextHudSub:@"连接失败" view:self.view];
                }
                
            }];
            
        }}

  

}




-(void)registed:(NSString*)sender{
    
    RegistedViewController* Login=[[RegistedViewController alloc]init];
    
    [self.navigationController pushViewController:Login animated:YES];
    
    
}

-(void)RongYun
{
    if ([[Global getRongYunToken] length]==0) {
        NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
        NSString* Token = [user objectForKey:@"tokenId"];
        if (Token.length>0) {
            [[RCIM sharedRCIM] initWithAppKey:@"x18ywvqf8p0ic"];//设置容云appKEY
            [self RequestRongYunToken];
            [[RCIM sharedRCIM] setUserInfoDataSource:self];
        }

    }
}
-(void)RequestRongYunToken
{
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSString* Token = [user objectForKey:@"tokenId"];
    if (Token ==nil) {
        Token=@"dd";
    }
    NSMutableDictionary *param = [NSMutableDictionary new];
    [param setValue:Token forKey:@"tokenId"];
    [param setValue:@"user" forKey:@"userType"];
    [param setValue:@"" forKey:@"memberId"];
    
    [HttpRequest requestData:@"Chat/RegChat" params:param success:^(BOOL isSuccess, SeverData *severDataDict) {
        
        if (isSuccess) {
            if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==0) {
                
                
                NSString *  rongYunToken=[[severDataDict.dataDict objectForKey:@"chatInfo"] objectForKey:@"chatToken"];
                [Global setRongYunToken:rongYunToken];
                [[RCIM sharedRCIM] connectWithToken:rongYunToken success:^(NSString *userId) {
                    
                } error:^(RCConnectErrorCode status) {
                    //                    NSLog(@"登陆的错误码为:%d", status);
                } tokenIncorrect:^{
                    //token过期或者不正确。
                    //如果设置了token有效期并且token过期，请重新请求您的服务器获取新的token
                    //如果没有设置token有效期却提示token错误，请检查您客户端和服务器的appkey是否匹配，还有检查您获取token的流程。
                    NSLog(@"token错误");
                }];
            }
            else{
                
                if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==9999) {
                    
                    
                    TheLoginViewController *detailViewController = [[TheLoginViewController alloc] init];
                    [self.navigationController pushViewController:detailViewController animated:YES];
                }
                
            }
            
        }
        else
        {
            [Global hideProgressHUDInternal:self.view];
            
            [Global showTextHudSub:@"连接失败" view:self.view];
        }
        
    }];
    
}

- (void)forgotPassword:(NSString *)forgotPassword{

     ForgotPasswordViewController*detailViewController = [[ForgotPasswordViewController alloc] init];
    [self.navigationController pushViewController:detailViewController animated:YES];


}

- (void)showAlertWait
{
    alt = [[UIAlertView alloc] initWithTitle:@"网络不稳定哦 ！" message:@"请确认网络" delegate:self cancelButtonTitle:nil otherButtonTitles: nil];
    [alt show];
    
    [self performSelector:@selector(hideAlert) withObject:nil afterDelay:1.0f];
    
}

- (void)showAlertMessage:(NSString *)msg
{
    alt = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:msg delegate:nil cancelButtonTitle:nil otherButtonTitles: nil];
    [alt show];
    
    [self performSelector:@selector(hideAlert) withObject:nil afterDelay:1.0f];
}
- (void)hideAlert
{
    if (alt != nil)
    {
        [alt dismissWithClickedButtonIndex:0 animated:YES];
        alt = nil;
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
